import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Login extends JPanel {

	private JTextField tFieldLogin;
	private JPasswordField tFieldPassword;

	/**
	 * Create the panel.
	 */
	public Login() {

		setBorder(new EmptyBorder(5, 5, 5, 5));
		setLayout(null);

		setSize(450, 300);

		JLabel lblUser = new JLabel("User:");
		lblUser.setBounds(75, 115, 75, 14);
		add(lblUser);

		JLabel lblPassword = new JLabel("Password:");
		lblPassword.setBounds(75, 140, 75, 14);
		add(lblPassword);

		tFieldLogin = new JTextField();
		tFieldLogin.setBounds(180, 112, 160, 20);
		add(tFieldLogin);
		tFieldLogin.setColumns(10);

		tFieldPassword = new JPasswordField();
		tFieldPassword.setBounds(180, 143, 160, 20);
		add(tFieldPassword);
		tFieldPassword.setColumns(10);

		JButton btnNewButton = new JButton("Login");
		btnNewButton.addActionListener(new ActionListener() {

			// verificar as credencias introduzidas enviando assim ao servidor
			public void actionPerformed(ActionEvent arg0) {
				InterfaceGrafica interfaceGrafica = InterfaceGrafica
						.getInstance();
				if (tFieldLogin.getText().trim().equals("")
						|| tFieldPassword.getText().equals("")) {
					JOptionPane.showMessageDialog(null,
							"Falta introduzir nome ou password");
				} else {
					String user = new String(tFieldLogin.getText() + " "
							+ tFieldPassword.getText());
					InterfaceGrafica.getCliente().login(user);
					while (interfaceGrafica.getEstadoLogin() == 0) {
						try {
							Thread.sleep(250);
						} catch (InterruptedException e) {
							System.out.println("Erro no sleep da Thread" + e);
						}
					}
					if (interfaceGrafica.getEstadoLogin() == 1)
						interfaceGrafica.getCardLayout().show(getParent(),
								"Principal");
					else {
						JOptionPane.showMessageDialog(null,
								"Login errado ou repositorios inexistentes");
						tFieldLogin.setText("");
						tFieldPassword.setText("");
					}
					interfaceGrafica.setEstadoLogin(0);
				}
			}
		});
		btnNewButton.setBounds(93, 188, 89, 23);
		add(btnNewButton);

		JButton btnNewButton_1 = new JButton("Cancelar");
		btnNewButton_1.setBounds(228, 188, 89, 23);
		add(btnNewButton_1);

	}
}
